#include "lineeditdelegate.h"

#include <QtGui/QLineEdit>

using namespace gui;

LineEditDelegate::LineEditDelegate(QWidget* parent) :
    QStyledItemDelegate(parent),
    m_role(Qt::EditRole),
    m_inputMask(),
    m_validator()
{

}

LineEditDelegate::~LineEditDelegate()
{

}

void LineEditDelegate::setRole(Qt::ItemDataRole role)
{
    m_role = role;
}

void LineEditDelegate::setInputMask(const QString& inputMask)
{
    m_inputMask = inputMask;
}

void LineEditDelegate::setValidator(
    const QSharedPointer<QValidator>& validator)
{
    m_validator = validator;
}

QWidget* LineEditDelegate::createEditor(QWidget* parent,
    const QStyleOptionViewItem& option,
    const QModelIndex& index) const
{
    QLineEdit* editor = new QLineEdit(parent);
    editor->setFrame(false);
    editor->installEventFilter(const_cast<LineEditDelegate* >(this));
    if (!m_inputMask.isEmpty())
    {
        editor->setInputMask(m_inputMask);
    }
    if (!m_validator.isNull())
    {
        editor->setValidator(m_validator.data());
    }

    return editor;
}

void LineEditDelegate::setEditorData(QWidget* editor,
    const QModelIndex& index) const
{
    QLineEdit* _editor = qobject_cast<QLineEdit* >(editor);

    QString text = index.data(m_role).toString();
    _editor->setText(text);
    _editor->selectAll();
}

void LineEditDelegate::setModelData(QWidget* editor,
    QAbstractItemModel* model,
    const QModelIndex& index) const
{
    QLineEdit* _editor = qobject_cast<QLineEdit* >(editor);

    if (_editor->hasAcceptableInput())
    {
        model->setData(index, _editor->text(), m_role);
    }
}

void LineEditDelegate::updateEditorGeometry(QWidget* editor,
    const QStyleOptionViewItem& option,
    const QModelIndex& index) const
{
    editor->setGeometry(option.rect);
}
